package editAir.buildEdit
{
	import _Pan3D.base.Camera3D;
	import _Pan3D.base.MakeModelData;
	import _Pan3D.base.ObjData;
	import _Pan3D.base.Object3D;
	import _Pan3D.base.ObjectHitBox;
	import _Pan3D.core.Calculation;
	import _Pan3D.core.Groundposition;
	import _Pan3D.core.Mathclass;
	import _Pan3D.core.TestTriangle;
	
	import _me.Scene_data;
	
	import editAir.editContent.ModelUiManege;
	
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Vector3D;
	
	import newPan3d.content.npc.NpcMenager;
	import editAir.editContent.ModelVO;


	
	public class BuildEditKeyControl extends EventDispatcher
	{
		private var _stage:Stage;
		private var _isFrist:Boolean=true;
		private var _keyobj:Object=new Object;
		private var _lastSelectID:uint=0;
		private static var _triangleClass:TestTriangle=new TestTriangle(); //引用一个测试类，


		public function BuildEditKeyControl()
		{
		}

		public function init(temp_stage:Stage):void
		{
			_stage=temp_stage;
			_stage.addEventListener("keyDown", keydownHandler);
			_stage.addEventListener("keyUp", keyupHandler);

			_stage.addEventListener(MouseEvent.MOUSE_DOWN, stageMouseDown);
			_stage.addEventListener(MouseEvent.MOUSE_MOVE, stageMouseMove);
			_stage.addEventListener(MouseEvent.MOUSE_UP, stageMouseUp);
			_stage.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheel);
			_stage.addEventListener(Event.ENTER_FRAME, onEnterFrame)
			_stage.addEventListener(MouseEvent.DOUBLE_CLICK, stageDoubleClik)
			_stage.doubleClickEnabled=true;

		}

		protected function stageDoubleClik(event:MouseEvent):void
		{


			if (!(event.target as Stage))
			{
				return;
			}
			var dpoint:Object3D=Groundposition.getScene3DPoint();
			var hitIt:Boolean=false;
			var tempevtVo:BuildEditDisplay3DSprite;
			var hitSprite:BuildEditDisplay3DSprite;
			var nearD:Number=1000;

			for each (var tempSprite:BuildEditDisplay3DSprite in BuildEditLevel.buildItem)
			{
				var a:Point=new Point(dpoint.x, dpoint.z);
				if (!tempSprite.objData)
				{
					continue;
				}
				var hitit:Boolean=testHitModel(tempSprite);

				var _D:Number=Mathclass.math_distance(tempSprite.x, tempSprite.z, dpoint.x, dpoint.z)

				if (hitit && tempSprite.isCanMove && _D < nearD)
				{
					nearD=_D;
					tempevtVo=tempSprite;

				}

			}
			if (tempevtVo&&tempevtVo.id!=_lastSelectID)
			{
				_lastSelectID=tempevtVo.id
				
				ModelUiManege.fileList.selectCell(tempevtVo.id)
				ModelUiManege.fileList.openFileFolderFater(tempevtVo.id)
				var tempModelVO:ModelVO=ModelUiManege.fileList.getSelectModelVoID()
				ModelUiManege.fileList.changePasition()
				if(tempModelVO){
					//trace("在多少行",tempModelVO.cell.y)
					if(tempModelVO.filetype==1&&tempModelVO.father==0){
						ModelUiManege.fileList.listScroll.setMcShowPositionY(tempModelVO.cell.y);
					}else{
						tempModelVO=ModelUiManege.fileList.getModelVobyID(tempModelVO.father)
						ModelUiManege.fileList.listScroll.setMcShowPositionY(tempModelVO.cell.y);
					}
					
				}
					
			}
			else
			{
				_lastSelectID=0;
				ModelUiManege.fileList.selectCell(ModelUiManege.fileList.getRandomNewId());
			}
			
		}

		protected function onEnterFrame(event:Event):void
		{
			// TODO Auto-generated method stub
			if (_keyobj[37])
			{
				Scene_data.focus3D.angle_y++
			}
			if (_keyobj[39])
			{
				Scene_data.focus3D.angle_y--
			}
		}

		private function stageMouseUp(event:MouseEvent):void
		{
			Scene_data.mouseInfo._mouseDown=false;

			if (event.target as Stage)
			{
			}
		}

		private function stageMouseMove(event:MouseEvent):void
		{
			if (Scene_data.mouseInfo._mouseDown)
			{
				var _E:Object3D=Groundposition._getposition(Scene_data.cam3D, Scene_data.stage.mouseX - Scene_data.stage3D.x, Scene_data.stage.mouseY - Scene_data.stage3D.y);


				if (EditManage.buildView.selectItem && EditManage.buildView.selectItem.length)
				{
					for (var i:int=0; i < EditManage.buildView.selectItem.length; i++)
					{
						var disp3DSprite:BuildEditDisplay3DSprite=EditManage.buildView.getBuildSpriteById(EditManage.buildView.selectItem[i]);
						if (disp3DSprite)
						{
							disp3DSprite.x=disp3DSprite.lastx + (_E.x - Scene_data.mouseInfo._last_x);
							disp3DSprite.z=disp3DSprite.lastz + (_E.z - Scene_data.mouseInfo._last_z);
							ModelUiManege.fileList.changeModelvoPosintAndScale(disp3DSprite);
						}

					}

				}
				else
				{

					Scene_data.focus3D.x=Scene_data.mouseInfo._old_x - (_E.x - Scene_data.mouseInfo._last_x);
					Scene_data.focus3D.z=Scene_data.mouseInfo._old_z - (_E.z - Scene_data.mouseInfo._last_z);
				}


			}
		}

		private var lastSprite3D:BuildEditDisplay3DSprite;

		private function testHitModel(tempSprite:BuildEditDisplay3DSprite):Boolean
		{
			var objData:ObjData=tempSprite.objData;
			//objData.hitbox.toString();
			var boxObjData:ObjData=MakeModelData.makeBoxTampData(objData.hitbox, tempSprite.scale);
			var hitit:Boolean=mathHitModel(boxObjData, new Vector3D(tempSprite.x, tempSprite.y, tempSprite.z))
			return hitit
		}

		private function mathHitModel(objData:ObjData, pos:Vector3D):Boolean
		{
			var A:Object3D=new Object3D;
			var B:Object3D=new Object3D;
			var C:Object3D=new Object3D;
			//复制镜头，因为这个新的镜头有别于原来;
			var _sceneCam:Camera3D=Scene_data.cam3D;
			var _thisCam:Camera3D=_sceneCam.clone();
			var f:Number=Scene_data.stage.mouseX - _sceneCam.fovw / 2;
			var g:Number=_sceneCam.fovh / 2 - Scene_data.stage.mouseY;
			_thisCam.x=_sceneCam.x;
			_thisCam.y=_sceneCam.y;
			_thisCam.z=_sceneCam.z;
			//镜头角度，逆方向，这样才可得到新的旋转后的这些点的镜头坐标。（或说，镜头向左转30度，其实就可以说这些点向右转30度）
			_thisCam.angle_y=-_sceneCam.angle_y;
			_thisCam.angle_x=-_sceneCam.angle_x;
			_thisCam.sin_x=Math.sin(_thisCam.angle_x * Math.PI / 180);
			_thisCam.cos_x=Math.cos(_thisCam.angle_x * Math.PI / 180);
			_thisCam.sin_y=Math.sin(_thisCam.angle_y * Math.PI / 180);
			_thisCam.cos_y=Math.cos(_thisCam.angle_y * Math.PI / 180);

			for (var i:int=0; i < objData.vertices.length / 9; i++)
			{
				A=new Object3D(objData.vertices[i * 9 + 0] + pos.x, objData.vertices[i * 9 + 1] + pos.y, objData.vertices[i * 9 + 2] + pos.z)
				B=new Object3D(objData.vertices[i * 9 + 3] + pos.x, objData.vertices[i * 9 + 4] + pos.y, objData.vertices[i * 9 + 5] + pos.z)
				C=new Object3D(objData.vertices[i * 9 + 6] + pos.x, objData.vertices[i * 9 + 7] + pos.y, objData.vertices[i * 9 + 8] + pos.z)

				math_change_point(_thisCam, A);
				math_change_point(_thisCam, B);
				math_change_point(_thisCam, C);

				//分析是否三点在同一线上
				if ((A.rx == B.rx && B.rx == C.rx) || (A.ry == B.ry && B.ry == C.ry) || (A.rz == B.rz && B.rz == C.rz))
				{
					continue;
				}

				//算出焦点f,g是屏幕坐标
				var P:Object3D=Calculation._get_hit_rec(A, B, C, Scene_data.cam3D, f, g);
				_triangleClass.setAllPoint(new Point(A.rx, A.ry), new Point(B.rx, B.ry), new Point(C.rx, C.ry))
				if (_triangleClass.checkPointIn(new Point(P.rx, P.ry)))
				{
					//有在三角形里胡就返回
					return true;
				}

			}
			return false;
		}

		private function math_change_point(_thisCam:Camera3D, _3dpoint:Object3D):void
		{
			//对坐标系里的原始点，跟据镜头角度算出新的从坐标
			var rx:Number=_3dpoint.x - _thisCam.x;
			var ry:Number=_3dpoint.y - _thisCam.y;
			var rz:Number=_3dpoint.z - _thisCam.z;

			//	var tmp_rx = this.rx;
			//	this.rx = int(Math.cos(tmp_angle)*tmp_rx-Math.sin(tmp_angle)*this.rz);
			//	this.rz = int(Math.sin(tmp_angle)*tmp_rx+Math.cos(tmp_angle)*this.rz);

			var tmp_rx:Number=rx;
			rx=_thisCam.cos_y * tmp_rx - _thisCam.sin_y * rz;
			rz=_thisCam.sin_y * tmp_rx + _thisCam.cos_y * rz;

			var tmp_rz:Number=rz;
			rz=_thisCam.cos_x * tmp_rz - _thisCam.sin_x * ry;
			ry=_thisCam.sin_x * tmp_rz + _thisCam.cos_x * ry;

			_3dpoint.rx=int(rx);
			_3dpoint.ry=int(ry);
			_3dpoint.rz=int(rz);
		}

		private function stageMouseDown(event:MouseEvent):void
		{

			if (!(event.target as Stage))
			{
				return;
			}

			var _E:Object3D=Groundposition._getposition(Scene_data.cam3D, Scene_data.stage.mouseX - Scene_data.stage3D.x, Scene_data.stage.mouseY - Scene_data.stage3D.y);

			Scene_data.mouseInfo._last_x=_E.x;
			Scene_data.mouseInfo._last_y=_E.y;
			Scene_data.mouseInfo._last_z=_E.z;

			if (EditManage.buildView.selectItem && EditManage.buildView.selectItem.length)
			{
				for (var i:int=0; i < EditManage.buildView.selectItem.length; i++)
				{
					var disp3DSprite:BuildEditDisplay3DSprite=EditManage.buildView.getBuildSpriteById(EditManage.buildView.selectItem[i]);
					if (disp3DSprite)
					{
						disp3DSprite.lastx=disp3DSprite.x;
						disp3DSprite.lasty=disp3DSprite.y;
						disp3DSprite.lastz=disp3DSprite.z;
					}
				}
			}
			else
			{
				Scene_data.mouseInfo._old_x=Scene_data.focus3D.x;
				Scene_data.mouseInfo._old_y=Scene_data.focus3D.y;
				Scene_data.mouseInfo._old_z=Scene_data.focus3D.z;
			}
			Scene_data.mouseInfo._mouseDown=true;
		}
		private var seepNum:Number=3;
		private function mouseWheel(evt:MouseEvent):void
		{
			if (!(evt.target is Stage))
				return;

			if (EditManage.buildView.selectItem && EditManage.buildView.selectItem.length)
			{
				var centenPosition:Vector3D=ModelUiManege.fileList.getSelectItemCenten(EditManage.buildView.selectItem)
	

				for (var i:int=0; i < EditManage.buildView.selectItem.length; i++)
				{
					var disp3DSprite:BuildEditDisplay3DSprite=EditManage.buildView.getBuildSpriteById(EditManage.buildView.selectItem[i]);
					if (disp3DSprite)
					{
						disp3DSprite.rotationY-=evt.delta

						var sin_y:Number=Math.sin(evt.delta * Math.PI / 180);
						var cos_y:Number=Math.cos(evt.delta * Math.PI / 180);
						var rx:Number=disp3DSprite.x - centenPosition.x;
						var rz:Number=disp3DSprite.z - centenPosition.z;
						var tmp_rx:Number=rx;
						rx=cos_y * tmp_rx - sin_y * rz;
						rz=sin_y * tmp_rx + cos_y * rz;
						disp3DSprite.x=rx + centenPosition.x;
						disp3DSprite.z=rz + centenPosition.z;
						
						 ModelUiManege.fileList.changeModelvoPosintAndScale(disp3DSprite);
						

					}
				}
			}
			else
			{
				Scene_data.cam3D.distance=Scene_data.cam3D.distance + evt.delta * 10;
			}
		}




		private function keydownHandler(evt:KeyboardEvent):void
		{
			_keyobj[evt.keyCode]=true;
			_isFrist=false;
			if (evt.keyCode == 87)
			{
				this.dispatchEvent(evt);
			}
		}

		private function keyupHandler(evt:KeyboardEvent):void
		{
			delete _keyobj[evt.keyCode];
			if (evt.keyCode == 87)
			{
				this.dispatchEvent(evt);
			}

		}

		public function isDown(key:Number):Boolean
		{
			return _keyobj[key] ? true : false;
		}
	}
}
